import Cookies from 'js-cookie';
import storage from '@/libs/storage';
import util from '@/libs/util';

const user = {
    state: {
        tokens: {},
        user: {}
    },
    mutations: {
        logout (state, vm) {
            storage.remove('tokens');
            // 清除自动更新Token
            clearInterval(window.refreshTokenTimer);

            storage.remove('user');
            Cookies.remove('user');

            state.tokens = {};
            state.user = {};

            // 恢复默认样式
            let themeLink = document.querySelector('link[name="theme"]');
            themeLink.setAttribute('href', '');
            // 清空打开的页面等数据，但是保存主题数据
            let theme = '';
            if (localStorage.theme) {
                theme = localStorage.theme;
            }
            localStorage.clear();
            if (theme) {
                localStorage.theme = theme;
            }
        },

        setTokens (state, tokens) {
            storage.set('tokens', tokens);
            state.tokens = tokens;

            clearInterval(window.refreshTokenTimer);
            if (tokens.hasOwnProperty('expires_in')) {
                window.refreshTokenTimer = setInterval(() => {
                    util.refreshToken();
                }, tokens.expires_in * 1000);
            }
        },

        setUser (state, user) {
            Cookies.set('user', user);
            storage.set('user', user);
            state.user = user;
        }
    },

    actions: {
        setTokens ({ commit }, tokens) {
            commit('setTokens', tokens);
        },

        setUser ({ commit }, user) {
            commit('setUser', user);
        }
    }
};

export default user;
